﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using NetWing.Model;//系统所有的model 都在这个命名空间里，这个还是比较有好处的。
using NetWing.BPM.Core;
using NetWing.Common;
using Omu.ValueInjecter;
using NetWing.Common.Data;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using NetWing.Common.Data.SqlServer;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;

namespace NetWing.BPM.Admin.psi.ashx
{
    /// <summary>
    /// Psi_OrderChu 的摘要说明
    /// </summary>
    public class Psi_OrderChu : IHttpHandler, IRequiresSessionState
    {
        public static long ConvertDateTimeToInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
            long t = (time.Ticks - startTime.Ticks) / 10000;   //除10000调整为13位      
            return t;
        }
        /// <summary>        
        /// 时间戳转为C#格式时间        
        /// </summary>        
        /// <param name=”timeStamp”></param>        
        /// <returns></returns>        
        private DateTime ConvertStringToDateTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
            var main = HttpContext.Current.Request["main"];//得到主表json数据
            var detail = HttpContext.Current.Request["detail"];//得到明细表json数据
            string edNumber = common.mjcommon.getedNumber("CH");
            int mainInsertedId = 0;//（主表公用）主表插入的ID
            int fmainInsertedId = 0;//财务主表插入的ID
            //这里可以执行一些逻辑
            if (string.IsNullOrEmpty(main) || string.IsNullOrEmpty(detail))
            {
                context.Response.Write("{\"status\":0,\"msg\":\"失败！主表或子表信息为空！\"}");
                context.Response.End();//输出结束
            }
            #region 主表处理
            var mainobj = JSONhelper.ConvertToObject<Psi_OrderModel>(main);//根据模型把json数据转化为obj
            Psi_OrderModel mainModel = new Psi_OrderModel();//初始化主表模型
            mainModel.InjectFrom(mainobj);//把obj插入模型
            mainModel.add_time = DateTime.Now;//给主表添加时间和更新时间赋值，其他字段赋值以此类推
            mainModel.up_time = DateTime.Now;
            mainModel.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID
            mainModel.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
            mainModel.orderType = "出货单";
            mainModel.edNumber = edNumber;
            #endregion

            #region 子表明细表处理
            JArray detailArr = JArray.Parse(detail);//把明细表转化为数组
            var k = detailArr[0].ToString();
            #endregion
            #region 数据库事务
            SqlTransaction tran = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
            try
            {
                //重要更新：用户取消进销存与财务关联。金额默认为0
                //主要改了fmainModel.payment=0;fmainModel.total=0;
                mainInsertedId = DbUtils.tranInsert(mainModel, tran);//往主表插入一条
                #region 财务主表处理
                //财务主表处理 方便以后财务统计s
                MJFinanceMainModel fmainModel = new MJFinanceMainModel();//初始化财务主表
                fmainModel.account = mainModel.paybank;//账号
                fmainModel.accountid = mainModel.paybankid;//账号ID
                fmainModel.add_time = DateTime.Now;
                fmainModel.contact = mainModel.Contacts;
                fmainModel.contactid = mainModel.ContactsId;
                //fmainModel.dep = dep;//部门
                fmainModel.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID
                fmainModel.edNumber = edNumber;
                fmainModel.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
                fmainModel.unit = mainModel.unit;//用户
                fmainModel.unitid = mainModel.unitid;//用户ID
                //fmainModel.note = "进销存主表id:"+mainInsertedId.ToString()+mainModel.Contacts + "出货收据，出货财务与系统财务取消关联金额为0，收支请到财务记账里记";
                fmainModel.note = "进销存主表id:" + mainInsertedId.ToString() + mainModel.Contacts + "";
                fmainModel.payment = mainModel.shifu;
                fmainModel.total = mainModel.total;
                fmainModel.operateid = int.Parse(SysVisitor.Instance.cookiesUserId);
                fmainModel.operate = SysVisitor.Instance.cookiesUserName;
                //fmainModel.note = mainInsertedId.ToString();//把插入的ID作为note
                fmainInsertedId = DbUtils.tranInsert(fmainModel, tran);//往财务主表插入一条
                                                                       //财务主表处理 方便以后财务统计e
                #endregion
                #region 财务明细表处理
                MJFinanceDetailModel fdetailModel = new MJFinanceDetailModel();//初始化明细表模型
                fdetailModel.financeId = fmainInsertedId;//财务主表ID
                fdetailModel.ftype = "";
                fdetailModel.edNumber = edNumber;
                fdetailModel.subject = "出货";
                fdetailModel.subjectid = 40;//40是出货
                fdetailModel.sumMoney = fmainModel.total;
                fdetailModel.dep = "";
                fdetailModel.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);
                fdetailModel.note = fmainModel.note;
                fdetailModel.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);
                fdetailModel.add_time = DateTime.Now;
                fdetailModel.up_time = DateTime.Now;
                DbUtils.tranInsert(fdetailModel, tran);//执行写入财务明细表
                #endregion
                //循环明细表
                for (int i = 0; i < detailArr.Count; i++)//有几条就执行几次
                {
                   

                    var detailobj = JSONhelper.ConvertToObject<Psi_BuyDetailsModel>(detailArr[i].ToString());//根据模型把明细表转化为obj
                    Psi_BuyDetailsModel detailModel = new Psi_BuyDetailsModel();//初始化明细表模型
                    detailModel.InjectFrom(detailobj);//把obj插入模型
                    detailModel.PsiOrderID = mainInsertedId;//父子表关联  养成一个习惯两表关联 字表里有 主表名+id 即主表id
                    detailModel.add_time = DateTime.Now;
                    detailModel.up_time = DateTime.Now; //每个都应该有up_time 和add_time
                    detailModel.orderType = mainModel.orderType;//单据类型
                    detailModel.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID
                    detailModel.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
                    detailModel.paybank = mainModel.paybank;//付款银行
                    detailModel.paybankid = mainModel.paybankid;//付款银行id
                    detailModel.unitname = mainModel.unit;//往来单位
                    detailModel.unitid = mainModel.unitid;
                    detailModel.unit_man = mainModel.unit_man;
                    detailModel.unit_moble = mainModel.unit_moble;
                    detailModel.Contacts = mainModel.Contacts;//联系人
                    detailModel.ContactsId = mainModel.ContactsId;//
                    detailModel.profit = (detailModel.sellPrice - detailModel.buyPrice) * detailModel.buyNum;//毛利=(售价-进价)*数量
                    detailModel.edNumber = edNumber;
                    detailModel.order_id = mainModel.aorder_id;
                    DbUtils.tranInsert(detailModel, tran);//执行写入明细表
                    //出子库存中的数据,前后推
                    DataTable data = SqlEasy.ExecuteDataTable("select * from psi_goodssuan where goodsNo='"+detailModel.goodsNo+"' and number>0 and status=0 order by KeyId asc");
                    int o = detailModel.buyNum;
                   
                    //string stoocksql = "update Psi_Goods set stock=stock-'" + o + "' where keyid=" + detailModel.goodsId + "";
                    //DbUtils.tranExecuteNonQuery(stoocksql, tran);
                    foreach (DataRow dr in data.Rows)
                    {
                        if(o > 0)
                        {
                            o = o - int.Parse(dr["number"].ToString());
                            if(o >= 0)
                            {
                                string stocksql = "update psi_goodssuan set up_time='"+DateTime.Now+"', number=0 where keyid=" + dr["keyid"].ToString() + "";
                                DbUtils.tranExecuteNonQuery(stocksql, tran);
                                //string stocksql = "update Psi_Goods set stock=" + abuynum + " where keyid=" + detailModel.goodsId + "";
                                Psi_goodssuanModel psi_Goodssuan = new Psi_goodssuanModel
                                {
                                    goodsID = detailModel.goodsId,
                                    goodsNo = detailModel.goodsNo,
                                    goodsName = detailModel.goodsName,
                                    goodsclassname = detailModel.goodsClassName,
                                    spercs = detailModel.specs,
                                    unit = detailModel.unit,
                                    up_time = DateTime.Now,
                                    status = "1",//1是出库
                                    number = 0,
                                    buyprice = Convert.ToDecimal(detailModel.sellPrice),
                                    add_time = DateTime.Now,
                                    stock = detailModel.buyNum
                                };
                                DbUtils.tranInsert(psi_Goodssuan, tran);
                                string sql = "select SUM(number) from psi_goodssuan where number!=0 and status=0 and goodsid='"+detailModel.goodsId+"'";
                                int abuynum = Convert.ToInt32(DbUtils.tranExecuteScalar(sql, tran));
                                //循环更新库存信息z
                                string stoocksql = "update Psi_Goods set stock=" + abuynum + " where keyid=" + detailModel.goodsId + "";
                                DbUtils.tranExecuteNonQuery(stoocksql, tran);
                            }
                            else
                            {
                                string stocksql = "update psi_goodssuan set number='"+Math.Abs(o)+"',up_time='"+DateTime.Now+"' where keyid=" + dr["keyid"].ToString() + "";
                                DbUtils.tranExecuteNonQuery(stocksql, tran);
                                //string stocksql = "update Psi_Goods set stock=" + abuynum + " where keyid=" + detailModel.goodsId + "";
                                Psi_goodssuanModel psi_Goodssuan = new Psi_goodssuanModel
                                {
                                    goodsID = detailModel.goodsId,
                                    goodsNo = detailModel.goodsNo,
                                    goodsName = detailModel.goodsName,
                                    goodsclassname = detailModel.goodsClassName,
                                    spercs = detailModel.specs,
                                    unit = detailModel.unit,
                                    up_time = DateTime.Now,
                                    status = "1",//1是出库
                                    number = Math.Abs(o),
                                    buyprice = Convert.ToDecimal(detailModel.sellPrice),
                                    add_time = DateTime.Now,
                                    stock = detailModel.buyNum

                                };
                                DbUtils.tranInsert(psi_Goodssuan, tran);
                                string sql = "select SUM(number) from psi_goodssuan where number!=0 and status=0 and goodsid='" + detailModel.goodsId + "'";
                                int abuynum = Convert.ToInt32(DbUtils.tranExecuteScalar(sql, tran));
                                //循环更新库存信息z
                                string stoocksql = "update Psi_Goods set stock=" + abuynum + " where keyid=" + detailModel.goodsId + "";
                                DbUtils.tranExecuteNonQuery(stoocksql, tran);
                            }
                        }
                    }
                    //出货的数量*分批的单价得到的总金额
                    //double buy;
                    ////用未减的库存减去已经用未减库存减出库的数量
                    //int buynumber;

                    ////这里主要是循环属于这个编号下的产品总条数
                    //foreach (DataRow row in data.Rows)
                    //{




                    //    //固定一个库存中实际数量
                    //    int buynumi = Convert.ToInt32(row["number"].ToString());
                    //    //用子库存中的实际数量减去要出库的数量,得到当前剩余的数量
                    //    int buynum = Convert.ToInt32(row["number"].ToString()) - detailModel.buyNum;
                    //    //用未减的库存减去已经用未减库存减出库的数量
                    //    buynumber = buynumi - buynum;
                    //    //如果时间库存数量减去出库数量>0
                    //    if (buynum > 0)
                    //    {
                    //        //long q = ConvertDateTimeToInt(DateTime.Parse(row["add_time"].ToString()));
                    //        //DateTime dateTime = Convert.ToDateTime(row["add_time"].ToString());
                    //        //string q = dateTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
                    //        //用减去的数量*单价得到出货的金额
                    //        buy = buynumber *  Convert.ToDouble(row["buyprice"].ToString());
                    //        //得到剩余库存并修改子库存表
                    //        //string hoo = "update psi_goodssuan set stock="+buynumber+",up_time='"+DateTime.Now+"' where add_time='"+row["add_time"].ToString()+"' and status=0";
                    //        int e = DbUtils.tranExecuteNonQuery("update psi_goodssuan set number=" + buynum + ",up_time='" + DateTime.Now.ToString() + "' where keyid='"+row["keyid"].ToString()+"' and status=0", tran);
                    //        //写一条出库记录到子库存
                    //Psi_goodssuanModel psi_Goodssuan = new Psi_goodssuanModel
                    //{
                    //    goodsID = detailModel.goodsId,
                    //    goodsNo = detailModel.goodsNo,
                    //    goodsName = detailModel.goodsName,
                    //    goodsclassname = detailModel.goodsClassName,
                    //    spercs = detailModel.specs,
                    //    unit = detailModel.unit,
                    //    up_time = DateTime.Now,
                    //    status = "1",//1是出库
                    //    number = buynumber,
                    //    buyprice = Convert.ToDecimal(detailModel.sellPrice),
                    //    add_time = Convert.ToDateTime(row["add_time"].ToString()),
                    //    stock = buynumi
                    //};
                    //        DbUtils.tranInsert(psi_Goodssuan, tran);
                    //        break;
                    //    }
                    //    //如果一条减不够那就在用一条减,直到出库数量达到
                    //    if (buynum < 0)
                    //    {
                    //        //当一条的库存不足时,循环下一页

                    //    }

                    //}
                }
                //循环明细表
                //事务的方法执行sql语句
                //可以写些什么逻辑放在这里
                //进货 减掉银行账户余额
                int c = DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance+" + mainModel.total + " where KeyId=" + mainModel.paybankid + "", tran);


                tran.Commit();//提交执行事务
                context.Response.Write("{\"status\":1,\"msg\":\"提交成功！\"}");
            }
            #endregion
            catch (Exception e)
            {
                tran.Rollback();//错误！事务回滚！
                context.Response.Write("{\"status\":0,\"msg\":\"" + e.ToString() + "\"}");
                WriteLogs.WriteLogsE("Logs", "DINGDError >> caozuo", e.Message + " >>> " + e.StackTrace);
                throw;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}